package edu.sctu.practice.class02.xuejiahua.assign08.ass02;

import edu.sctu.practice.class01.huangtianlin.assign6.guava.Client;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * Created by Dom_xuejiahua on 2015/12/24.
 */
public class User extends Frame implements Runnable,ActionListener {
    Button connection;
    Socket socket = null;
    ObjectInputStream in = null;
    ObjectOutputStream out = null;
    Thread thread;

    public User() {
        socket = new Socket();
        connection = new Button("连接服务器,读取文本区对象");
        add(connection, BorderLayout.NORTH);
        connection.addActionListener(this);
        thread = new Thread(this);
        setBounds(100, 100, 360, 310);
        setVisible(true);
        addWindowListener(new WindowAdapter() {
                              public void windowClosing(WindowEvent e) {
                                  System.exit(0);
                              }
                          }
        );
    }

    public void run() {
        while (true) {
            try {
                TextArea text = (TextArea) in.readObject();
                add(text, BorderLayout.CENTER);
                validate();
            } catch (Exception e) {
                break;
            }
        }
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == connection) {
            try {
                if (socket.isConnected()) {
                } else {
                    InetAddress address = InetAddress.getByName("127.0.0.1");
                    InetSocketAddress socketAddress = new InetSocketAddress(address, 4331);//创建端口为4331、地址为
                    //address的socketAddress
                    socket.connect(socketAddress);  //socket建立和socketAddress的连接呼叫。
                    in = new ObjectInputStream(socket.getInputStream()); //socket返回输入流
                    out = new ObjectOutputStream(socket.getOutputStream()); //socket返回输出流
                    thread.start();
                }
            } catch (Exception ee) {
            }
        }
    }
    public static void main(String args[]) {
        Client win = new Client();
    }

}


